<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */


class aftersales_ctl_admin_returnproduct extends desktop_controller{
    // public $workground = 'ectools_ctl_admin_order';
    var $certcheck = false;

    public function __construct($app)
    {
        parent::__construct($app);
        header("cache-control: no-store, no-cache, must-revalidate");
        $this->arr_status = array(
            '1' => app::get('aftersales')->_('申请中'),
            '2' => app::get('aftersales')->_('审核中'),
            '3' => app::get('aftersales')->_('接受申请'),
            '4' => app::get('aftersales')->_('完成'),
            '5' => app::get('aftersales')->_('拒绝'),
        );
        $this->objMath = kernel::single('ectools_math');
    }

    public function index()
    {
        $this->workground = 'ectools.wrokground.order';
        if($_GET['action'] == 'export') $this->_end_message = '导出售后服务申请';
        $this->finder('aftersales_mdl_return_product',array(
            'title'=>app::get('aftersales')->_('售后服务管理'),
            'actions'=>array(
                        ),
            'use_buildin_set_tag'=>true,
            'use_buildin_recycle'=>false,
            'use_buildin_filter'=>true,
            'use_view_tab'=>true,
            ));
    }

    /**
     * 桌面订单相信汇总显示
     * @param null
     * @return null
     */
    public function _views(){
        $mdl_aftersales = $this->app->model('return_product');
        $sub_menu = array(
            1=>array('label'=>app::get('aftersales')->_('审核中'),'optional'=>false,'filter'=>array('status'=>2,'disabled'=>'false')),
            2=>array('label'=>app::get('aftersales')->_('接受申请'),'optional'=>false,'filter'=>array('status'=>3,'disabled'=>'false')),
            3=>array('label'=>app::get('aftersales')->_('完成'),'optional'=>false,'filter'=>array('status'=>4,'disabled'=>'false')),
            4=>array('label'=>app::get('aftersales')->_('拒绝'),'optional'=>false,'filter'=>array('status'=>5,'disabled'=>'false')),
            5=>array('label'=>app::get('aftersales')->_('全部'),'optional'=>false,'filter'=>array('disabled'=>'false')),
        );

        if(isset($_GET['optional_view'])) $sub_menu[$_GET['optional_view']]['optional'] = false;

        foreach($sub_menu as $k=>$v){
            if($v['optional']==false){
                $show_menu[$k] = $v;
                if(is_array($v['filter'])){
                    $v['filter'] = array_merge(array(),$v['filter']);
                }else{
                    $v['filter'] = array();
                }
                $show_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
                if($k==$_GET['view']){
                    $show_menu[$k]['newcount'] = true;
                    $show_menu[$k]['addon'] = $mdl_aftersales->count($v['filter']);
                }
                $show_menu[$k]['href'] = 'index.php?app=aftersales&ctl=admin_returnproduct&act=index&view='.($k).(isset($_GET['optional_view'])?'&optional_view='.$_GET['optional_view'].'&view_from=dashboard':'');
            }elseif(($_GET['view_from']=='dashboard')&&$k==$_GET['view']){
                $show_menu[$k] = $v;
            }
        }

        return $show_menu;
    }

    public function gorefund($return_id, $order_id)
    {
        $obj_return_product = app::get('aftersales')->model('return_product');
        $objOrder = app::get('b2c')->model('orders');
        $arr_return_product = $obj_return_product->dump($return_id);
        if ($arr_return_product['comment'])
            $arr_return_product['comment'] = unserialize($arr_return_product['comment']);
        if ($arr_return_product['product_data'])
            $arr_return_product['product_data'] = unserialize($arr_return_product['product_data']);

        $this->pagedata['info'] = $arr_return_product;
        $this->pagedata['orderinfo'] = app::get('b2c')->model('order_items')->getList('bn, name, nums, price', array('order_id'=>$order_id));
        $this->pagedata['return_id'] = $return_id;
        
        $aORet = $objOrder->dump($order_id);
        $this->pagedata['order'] = $aORet;

        $opayment = app::get('ectools')->model('payment_cfgs');
        $this->pagedata['payment'] = $opayment->getList('*', array('status' => 'true', 'platform'=>array('iscommon','ispc'), 'is_frontend' => true, 'app_id'=>$this->pagedata['order']['payinfo']['pay_app_id']));

        $refund_amount = 0;
        foreach($arr_return_product['product_data'] as $val){
            $refund_amount += $val['refund_amount'];
        }
        
        //$this->pagedata['refund_amount'] = number_format(floor($refund_amount / $aORet['cost_item'] * ($aORet['total_amount'] - $aORet['cost_payment']) * 100) / 100, 2, '.', '');
        $this->pagedata['refund_amount'] = $refund_amount;

        $this->display('admin/return_product/gorefund.html');
    }

    public function dorefund()
    {
        $this->begin();
        if(!$_POST["order_id"] || !$_POST["return_id"]){
            $this->end(false, "必要参数缺失");
        }

        $obj_return_product = app::get('aftersales')->model('return_product');
        $arr_return_product = $obj_return_product->dump($_POST['return_id']);
        if($arr_return_product['status'] != '4' && $arr_return_product['status'] != '6'){
            $this->end(false, "仓库未收货不能退款");
        }elseif($arr_return_product['refund_status'] == '1'){
            $this->end(false, "已对此售后申请做过退款操作了");
        }
        
        $refund_amount = 0;//退款金额
        if ($arr_return_product['product_data']){
            $product_data = unserialize($arr_return_product['product_data']);
            foreach($product_data as $v){
                if($v['refund_amount']){
                    $refund_amount += $v['refund_amount'];
                }                
            }
        }
        
        if( ! $refund_amount) {
            $this->end(false, "退款金额不能为0");
        }
            
        $obj_order = app::get('b2c')->model('orders');
        $subsdf = array('order_objects'=>array('*',array('order_items'=>array('*',array(':products'=>'*')))));
        $sdf_order = $obj_order->dump($_POST['order_id'],'*',$subsdf);
        
        //临时判断，如果退款金额大于已付款金额，按已付款金额退款
        if($refund_amount > $sdf_order['payed']){
            $refund_amount = $sdf_order['payed'];
        }

        //退款
        $sdf = array(
            'order_id' => $_POST['order_id'],
            'money' => floatval($refund_amount),
            'return_score' => intval($_POST['return_score']),
        );

        $obj_checkorder = kernel::service('b2c_order_apps', array('content_path'=>'b2c_order_checkorder'));
        if (!$obj_checkorder->check_order_refund($sdf['order_id'], $sdf, $message))
        {
            $this->end(false, $message);
        }

        //zenngxinwen
        $sdf['score_u'] = $sdf_order['score_u'];
        //end

        $objPaymemtcfg = app::get('ectools')->model('payment_cfgs');
        $sdf['payment'] = ($_POST['payment']) ? $_POST['payment'] : $sdf_order['payinfo']['pay_app_id'];
        if ($sdf['payment'] == '-1')
        {
            $arrPaymentInfo['app_name'] = app::get('b2c')->_("货到付款");
            $arrPaymentInfo['app_version'] = "1.0";
        } else {
            $arrPaymentInfo = $objPaymemtcfg->getPaymentInfo($sdf['payment']);
        }            
        
        $refunds = app::get('ectools')->model('refunds');
        $time = time();
        $sdf['refund_id'] = $refunds->gen_id();
        $sdf['pay_app_id'] = $sdf['payment'];
        $sdf['member_id'] = $sdf_order['member_id'] ? $sdf_order['member_id'] : 0;
        $sdf['currency'] = $sdf_order['currency'];
        $sdf['paycost'] = 0;
        $sdf['total_amount'] = $sdf_order['total_amount'];
        $sdf['cur_money'] = $sdf['money'];
        $sdf['money'] = $this->objMath->number_div(array($sdf['cur_money'], $sdf_order['cur_rate']));
        $sdf['t_begin'] = $time;
        $sdf['t_payed'] = $time;
        $sdf['t_confirm'] = $time;
        $sdf['pay_object'] = 'order';
        $sdf['op_id'] = $this->user->user_id;
        $sdf['op_name'] = $this->user->user_data['account']['login_name'];
        $sdf['status'] = 'ready';
        $sdf['app_name'] = $arrPaymentInfo['app_name'];
        $sdf['app_version'] = $arrPaymentInfo['app_version'];
        $obj_refunds = kernel::single("ectools_refund");
        if ($obj_refunds->generate($sdf, $this, $msg))
        {
            $is_refund_finished = false;
            $obj_refund_lists = kernel::servicelist("order.refund_finish");
            foreach ($obj_refund_lists as $order_refund_service_object){
                $is_refund_finished = $order_refund_service_object->order_refund_finish($sdf, 'succ', 'Back',$msg);
            }
            if ($is_refund_finished){
                $refund = array(
                    'refund_status'=>'1',
                    'refunded' => $sdf['money']
                );
                if($obj_return_product->update($refund, array('return_id'=>$_POST['return_id'])))
                {
                    // 发送同步日志.
                    $order_refund_service_object->send_request($sdf);
                    $this->end(true, app::get('b2c')->_('退款成功'));
                }else{
                    $this->end(false, app::get('b2c')->_('退款状态更新失败'));
                }
            }else{
                $this->end(false, $msg);
            }
        } else {
            $this->end(false, $msg);
        }
    }

    public function save()
    {
        $rp = $this->app->model('return_product');
        $obj_return_policy = kernel::single('aftersales_data_return_policy');

        $return_id = $_POST['return_id'];
        $status = $_POST['status'];
        $sdf = array(
            'return_id' => $return_id,
            'status' => $status,
        );
        $this->pagedata['return_status'] = $obj_return_policy->change_status($sdf);
        if ($this->pagedata['return_status']){
            $this->pagedata['return_status'] = $this->arr_status[$this->pagedata['return_status']];
        }    

        $obj_aftersales = kernel::servicelist("api.aftersales.request");
        foreach ($obj_aftersales as $obj_request) {
            $obj_request->send_update_request($sdf);
        }

        $this->display('admin/return_product/return_status.html');
    }

    public function new_save()
    {
        $this->begin();
        $mdl_return_product = $this->app->model('return_product');
        $obj_return_policy = kernel::single('aftersales_data_return_policy');

        //更新售后退款金额
        $refund_amount = $_POST['refund_amount'];
        $return_id = $_POST['return_id'];
        if($refund_amount){
            $returnInfo = $mdl_return_product->dump($return_id);
            $mdl_orders = app::get('b2c')->model('orders'); 
            $rs_orders = $mdl_orders->dump($returnInfo['order_id']);
            $final_amount = $rs_orders['cur_amount'] - $rs_orders['shipping']['cost_shipping'];
            if($returnInfo){
                $product_data = unserialize($returnInfo['product_data']);
                foreach ($product_data as  &$v){
                    
                    //判断最大退款金额
                    $goods_amount = $v['price'] * $v['num'];
                    $item_ratio = $goods_amount / $rs_orders['cost_item'];
                    $max_refund_amount = round($final_amount * $item_ratio, 2); //最大退款金额
                    $max_refund_amount += $rs_orders['shipping']['cost_shipping'];
                    if($refund_amount[$v['product_id']] > $max_refund_amount){
                        $this->end(false, "最大退款金额不能超过 {$max_refund_amount}");
                    }
                    
                    $v['refund_amount'] = $refund_amount[$v['product_id']];
                }
                $product_data = serialize($product_data);
                $mdl_return_product->update(
                    array('product_data'=>$product_data), 
                    array('return_id'=>$return_id)
                );
            }
        }
        
        //更新售后状态
        $status = $_POST['status'];
        $sdf = array(
            'return_id' => $return_id,
            'status' => $status,
        );
        $this->pagedata['return_status'] = $obj_return_policy->change_status($sdf);
        if ($this->pagedata['return_status']){
            $this->pagedata['return_status'] = $this->arr_status[$this->pagedata['return_status']];
        }            

        $obj_aftersales = kernel::servicelist("api.aftersales.request");
        foreach ($obj_aftersales as $obj_request) {
            $obj_request->send_update_request($sdf);
        }
        $this->end(true, '保存成功');
    }

    public function file_download($return_id)
    {
        $obj_return_policy = kernel::service("aftersales.return_policy");
        $obj_return_policy->file_download($return_id);
    }

    public function send_comment()
    {
        $rp = $this->app->model('return_product');

        $return_id = $_POST['return_id'];
        $comment = $_POST['comment'];
        $arr_data = array(
            'return_id' => $return_id,
            'comment' => $comment,
        );

        $this->begin();
        if($rp->send_comment($arr_data))
        {
            $this->end(true, app::get('aftersales')->_('发送成功！'));
        }
        else
        {
            //trigger_error(__('发送失败'),E_USER_ERROR);
            $this->end(false, app::get('aftersales')->_('发送失败！'));
        }
    }

    public function settings()
    {
        $this->workground = 'site.wrokground.theme';
        if (!$_POST)
        {
            $this->pagedata['return_product']['comment'] = app::get('aftersales')->getConf('site.return_product_comment');
            $this->page('admin/setting/return_product.html');
        }
        else
        {
            $this->begin('index.php?app=aftersales&ctl=admin_returnproduct&act=settings');

            app::get('aftersales')->setConf('site.return_product_comment', $_POST['conmment']);

            $this->end(true, app::get('aftersales')->_("设置成功！"));
        }
    }

    public function accept($oid, $return_id)
    {
        $mdl_orders = app::get('b2c')->model('orders');
        $rs_orders = $mdl_orders->dump($oid);
        $this->pagedata['order_info'] = $rs_orders;
        $this->pagedata['return_id'] = $return_id;
        
        //售后单明细
        $obj_return_policy = kernel::service("aftersales.return_policy");
        $return_data = $obj_return_policy->get_return_product_by_return_id($return_id);
        //echo('<pre>');var_dump($return_items);

        //商品单个总价格=(订单支付金额-运费)* 商品金额 / 商品总金额
        $final_amount = $rs_orders['cur_amount'] - $rs_orders['shipping']['cost_shipping'];

        if($return_data){
            foreach ($return_data['product_data'] as &$v){
                $goods_amount = $v['price'] * $v['num'];
                $item_ratio = $goods_amount / $rs_orders['cost_item'];
                $v['refund_amount'] = round($final_amount * $item_ratio, 2); //退款金额
                if($v['refund_amount'] < 0){
                    $v['refund_amount'] = 0;
                }
            }
        }
        
        $this->pagedata['return_data'] = $return_data;
        $this->display('admin/return_product/accept.html');
    }
}
